use config::Config;
use serde::Deserialize;
use sq_global::CONFIG_FILE;
use std::fs;
use std::sync::OnceLock;

static CONFIG: OnceLock<Config> = OnceLock::new();
#[inline]
fn val() -> &'static Config {
    CONFIG.get().expect("Config is not initialized")
}

pub fn init() {
    let path = fs::canonicalize(CONFIG_FILE)
        .unwrap_or_else(|e| panic!("cannot find config file!!!：{} - {}", e, CONFIG_FILE));

    let file = path.to_str().expect("config path to str err !!!");

    let config = Config::builder()
        .add_source(config::File::with_name(file))
        .build()
        .unwrap_or_else(|e| panic!("config file load failed!!!：{}", e));
    CONFIG.set(config).expect("init config err !!!")
}

//程序运行期使用
pub fn get<'de, T: Deserialize<'de>>(key: &str) -> Result<T, anyhow::Error> {
    val().get::<T>(key).map_err(|e| anyhow::anyhow!(e))
}

//只在程序启动期使用，运行期不要使用！
pub fn get_unchecked<'de, T: Deserialize<'de>>(key: &str) -> T {
    val()
        .get::<T>(key)
        .unwrap_or_else(|_| panic!("cannot find config key {key}"))
}
